package itbour.onetouchshow.activity.challengezone.filter;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.andview.adapter.ABaseRefreshAdapter;
import com.andview.adapter.BaseRecyclerHolder;
import com.andview.listener.OnItemClickListener;
import com.gpu.clipper.VideoClipper;
import com.gup.video.GPUImageExtTexFilter;
import com.gup.video.GPUImageFilterGroup;
import com.gup.video.GPUImageFilterTools;
import com.gup.video.MovieWrapperView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import itbour.onetouchshow.App;
import itbour.onetouchshow.R;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.bean.EffectsBean;
import itbour.onetouchshow.bean.PersonalCreateConfigBean;
import itbour.onetouchshow.bean.user.UserMakeTag;
import itbour.onetouchshow.constants.AppConfig;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.listener.OnMultiClickListener;
import itbour.onetouchshow.service.HomeKeyWatcher;
import itbour.onetouchshow.utils.AssetsDataUtils;
import itbour.onetouchshow.utils.FileUtils;
import itbour.onetouchshow.utils.ImageLoader;
import itbour.onetouchshow.utils.SpUtils;
import itbour.onetouchshow.utils.TypeCastHelper;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.aliyun.AliRequestUtils;
import jp.co.cyberagent.android.gpuimage.GPUImageColorMatrixFilter;
import jp.co.cyberagent.android.gpuimage.GPUImageFilter;
import jp.co.cyberagent.android.gpuimage.GPUImageMonochromeFilter;
import jp.co.cyberagent.android.gpuimage.GPUImageSketchFilter;

import static itbour.onetouchshow.utils.UIUtils.getContext;
import static itbour.onetouchshow.utils.UIUtils.runInMainThread;

/**
 * Created by Administrator on 2018/7/25.
 */

public class VideoWaterActivity extends MVPBaseActivity {
    static final int VIDEO_CUT_FINISH = 4;
    static final int VIDEO_CUT_JUMP = 5;
    static final int VIDEO_PLAY = 6;
    protected boolean pressedHome;
    @BindView(R.id.video_prew)
    MovieWrapperView videoPreviewView;
    @BindView(R.id.filter_listView)
    RecyclerView mFilterListView;
    @BindView(R.id.layout_filter)
    LinearLayout mFilterLayout;
    @BindView(R.id.tv_text_edit)
    TextView tvTextEdit;
    @BindView(R.id.ly_text_edit)
    LinearLayout lyTextEdit;
    @BindView(R.id.tv_text_save)
    TextView tvTextSave;
    @BindView(R.id.tv_text_cut)
    TextView tvTextCut;
    @BindView(R.id.ly_text_cut)
    LinearLayout lyTextCut;
    @BindView(R.id.id_ig_close)
    ImageView closeFilterLayout;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.id_tv_filter_name)
    TextView tvFilterName;
    @BindView(R.id.id_root_hint)
    LinearLayout rootHint;
    List<EffectsBean> filtersBeans;
    OneToucDialog oneToucDialog;
    boolean isUpdate = false;
    String localVideoUrl;
    FilterAdapter filterAdapter;
    boolean isShow;
    GPUImageFilter hisGpuImageFilter;
    OSSAsyncTask<PutObjectResult> putObjectResultOSSAsyncTask;
    VideoClipper clipper;
    private EffectsBean hiseffectsBean;
    private EffectsBean cureffectsBean;
    private HomeKeyWatcher mHomeKeyWatcher;
    private ObjectAnimator animator;
    private GPUImageFilter currentFilter;
    private int videoId;
    private String videoUrl;
    private int currentPosition = -1;
    private String videoPath;
    /**
     * 设置滤镜的路径
     */
    private String processedUrl;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case VIDEO_CUT_FINISH:
                    cliptAndSave();
                    break;
                case VIDEO_CUT_JUMP:
                    Intent launchIntent = VideoTimmerCutActivity.getLaunchIntent(getContext(), videoUrl, UserMakeTag.CUTUPDATE.getTypeName());
                    startActivity(launchIntent);
                    break;
                case VIDEO_PLAY:
                    dismissProgressDialog();
                    SpUtils.getInstance().saveString(videoUrl, videoPath);
                    videoPreviewView.setVideoPath(videoUrl);
                    break;
            }
        }
    };

    public static Intent getLaunchIntent(Context context, String vidoUrl, int videoId, EffectsBean effectsBean) {
        Intent intent = new Intent(context, VideoWaterActivity.class);
        intent.putExtra(AppConst.KEY_VIDEO_EFFECTSBEAN, effectsBean);
        intent.putExtra(AppConst.KEY_VIDEO_PRODUCT_ID, videoId);
        intent.putExtra(AppConst.KEY_VIDEO_URL, vidoUrl);
        return intent;
    }

    //获取VideoPath
    public static String getPath(String path, String fileName) {
        String p = FileUtils.getDownloadDir() + path;
        File f = new File(p);
        if (!f.exists() && !f.mkdirs()) {
            return FileUtils.getDownloadDir() + fileName;
        }
        return p + fileName;
    }

    public void showNewDialog() {
        OneToucDialog.Builder builder = new OneToucDialog.Builder(this);
        builder.content("视频上传中");
        oneToucDialog = builder.setType(OneToucDialog.Builder.ONE_TOUCH_TYPE_DOWNLOAD)
                .cancelable(false).setShowDownloadProgress(true).setmWidth(AppConst.APP_DIALOG_WIDTH)
                .show();
    }

    public void cliptAndSave() {
        showNewDialog();
        String Video = ".mp4";
        String videoName = AliRequestUtils.getInstance().createFileName("video", App.getLoginBean().getUserInfo().getUserId() + "") + Video;
        String IMAGE = ".png";
        String imageName = AliRequestUtils.getInstance().createFileName("image", App.getLoginBean().getUserInfo().getUserId() + "") + IMAGE;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap videoThumbnail = ImageLoader.getInstance().getVideoThumbnail(localVideoUrl);
                    AliRequestUtils.getInstance().setName(imageName);
                    File imagefile = AliRequestUtils.getInstance().saveBitmapFile(videoThumbnail, FileUtils.getJpgFileName(localVideoUrl));
                    App.ossClient.putObject(AliRequestUtils.getInstance().putObjectRequest(imagefile.getAbsolutePath()));
                    //App.ossClient.putObject(list.get(0));
                    String imagePathName = AppConfig.UPLOAD_ALYUN + imageName;
                    AliRequestUtils.getInstance().setName(videoName);
                    PutObjectRequest put = new PutObjectRequest(AppConst.OSSBUCKETNAME, videoName, localVideoUrl);
                    // 异步上传时可以设置进度回调
                    put.setProgressCallback((request, currentSize, totalSize) -> {
                        int progress = (int) (currentSize * 100 / totalSize);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                oneToucDialog.setTvprogress(progress + "% ");
                                oneToucDialog.setDownloadProgress(progress);
                            }
                        });

                    });
                    putObjectResultOSSAsyncTask = App.ossClient.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                        @Override
                        public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                            Log.d("PutObject", "UploadSuccess");
                            Log.d("ETag", result.getETag());
                            Log.d("RequestId", result.getRequestId());
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    processedUrl = AppConfig.UPLOAD_ALYUN + videoName;
                                    UserMakeTag userMakeTag = UserMakeTag.UPDATE;
                                    //存储本地路径和网络路径对应  网络路径对应本地路径
                                    //SpUtils.getInstance().saveString(videoPathfile, videoUrl);
                                    cureffectsBean.setId(videoId);
                                    userMakeTag.setTag(videoUrl);
                                    userMakeTag.setTag1(videoId + "");
                                    userMakeTag.setTag2(processedUrl);
                                    userMakeTag.setEffectsBean(cureffectsBean);
                                    EventBus.getDefault().post(userMakeTag);
                                    oneToucDialog.dismiss();
                                    finish();
                                }
                            });

                        }

                        @Override
                        public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                            // 请求异常
                            oneToucDialog.dismiss();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    oneToucDialog.dismiss();
                }
            }
        }).start();
    }

    @Override
    public void loadSucceed(String result) {
    }

    @Override
    public void loadFaild(String error) {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_video_water;
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        tvNext.setText("保存");
        tvSave.setText("删除");
        tvNext.setTextColor(UIUtils.getColor(R.color.white));
        tvNext.setEnabled(true);
        tvSave.setTextColor(UIUtils.getColor(R.color.white));
        tvSave.setEnabled(true);

    }

    public void deleteVideoDialog() {
        new OneToucDialog.Builder(this)
                .content("确定删除此镜头吗?").negativeText("取消").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                Log.e("TAH", "点击取消");
            }
        }).positiveText("删除").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                UserMakeTag userMakeTag = UserMakeTag.DELETEVIDEO;
                userMakeTag.setTag(videoId + "");
                EventBus.getDefault().post(userMakeTag);
                finish();
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false)
                .show();
    }

    @Override
    public void finish() {
        if (putObjectResultOSSAsyncTask != null) {
            putObjectResultOSSAsyncTask.cancel();
        }
        if (mHandler != null) {
            mHandler = null;
        }
        if (clipper != null) {
            clipper.release();
        }
        super.finish();
    }

    @Override
    public void onBackPressed() {
        dismissProgressDialog();
        if (videoPreviewView.onBackPress()) {
            return;
        }
        if (isUpdate) {
            showSaveDialog();
            return;
        }
        if (hiseffectsBean == null && cureffectsBean == null) {
            super.onBackPressed();
        } else if (hiseffectsBean == null && cureffectsBean != null) {
            showSaveDialog();
        } else {
            if (hiseffectsBean.getCt() == cureffectsBean.getCt()) {
                super.onBackPressed();
            } else {
                showSaveDialog();
            }

        }
    }

    public void showSaveDialog() {
        new OneToucDialog.Builder(this)
                .content("是否保存本次编辑并退出")
                .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                if (cureffectsBean == null) {
                    //只修改本地路径
                    UserMakeTag userMakeTag = UserMakeTag.UPDATE;
                    userMakeTag.setTag(videoUrl);
                    userMakeTag.setTag1(videoId + "");
                    userMakeTag.setTag2(videoUrl);
                    EventBus.getDefault().post(userMakeTag);
                    finish();
                } else {
                    showProgressDialogWithText("视频处理中");
                    setFileterDownloadFile();
                }

            }
        })
                .negativeText("取消").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                finish();
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false)
                .show();


    }

    @Override
    protected void onPause() {
        videoPreviewView.pause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        videoPreviewView.resume();
        super.onResume();

    }

    @Override
    protected void onStop() {
        mHomeKeyWatcher.stopWatch();
        super.onStop();
    }

    @Override
    protected void onRestart() {
        mHomeKeyWatcher.startWatch();
        pressedHome = false;
        super.onRestart();
    }

    @Override
    protected void onDestroy() {
        if (videoPreviewView != null) {
            videoPreviewView.getVideoPreviewView().onDestroy();
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        Bundle extras = getIntent().getExtras();
        videoUrl = extras.getString(AppConst.KEY_VIDEO_URL);
        videoId = extras.getInt(AppConst.KEY_VIDEO_PRODUCT_ID);
        hiseffectsBean = (EffectsBean) getIntent().getSerializableExtra(AppConst.KEY_VIDEO_EFFECTSBEAN);
        localVideoUrl = SpUtils.getInstance().getString(videoUrl);
        if (TextUtils.isEmpty(localVideoUrl)) {
            //TODO  执行下载操作
            AssetsDataUtils.doDonwloadVideo(videoUrl, new AssetsDataUtils.DownLoadVideoListener() {
                @Override
                public void onSuccess(String path) {
                    videoPath = path;
                    mHandler.sendEmptyMessage(VIDEO_PLAY);
                }

                @Override
                public void onFail() {
                }
            });
        } else {
            UIUtils.videoWHDA(localVideoUrl);
            videoPreviewView.setVideoPath(localVideoUrl);
        }


        if (hiseffectsBean != null) {
            cureffectsBean = hiseffectsBean;
            hisGpuImageFilter = getmFilter(hiseffectsBean);
            switchFilterTo(hisGpuImageFilter);
        }

        lyTextEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (hiseffectsBean != null) {
                    int selectPostion = getSelectPostion(hiseffectsBean);
                    filterAdapter.setSelect(selectPostion);
                }
                showFilters();

            }
        });
        tvNext.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                if (currentPosition == -1 || cureffectsBean == null) {
                    tvNext.setEnabled(false);
                    if (isUpdate) {
                        //只修改本地路径
                        UserMakeTag userMakeTag = UserMakeTag.UPDATE;
                        userMakeTag.setTag(videoUrl);
                        userMakeTag.setTag1(videoId + "");
                        userMakeTag.setTag2(videoUrl);
                        EventBus.getDefault().post(userMakeTag);
                        finish();
                    } else {
                        finish();
                    }
                } else {
                    runInMainThread(new Runnable() {
                        @Override
                        public void run() {
                            showProgressDialogWithText("视频处理中");
                            setFileterDownloadFile();
                        }
                    });

                }
            }
        });

        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        deleteVideoDialog();
                    }
                });
            }
        });

        tvTextCut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.sendEmptyMessage(VIDEO_CUT_JUMP);
            }
        });
        lyTextCut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.sendEmptyMessage(VIDEO_CUT_JUMP);
            }
        });

        iv_back.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                onBackPressed();
            }
        });
        mHomeKeyWatcher = new HomeKeyWatcher(this);
        mHomeKeyWatcher.setOnHomePressedListener(new HomeKeyWatcher.OnHomePressedListener() {
            @Override
            public void onHomePressed() {
                pressedHome = true;
            }
        });
        pressedHome = false;
        mHomeKeyWatcher.startWatch();
        rootHint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShow) {
                    hideFilters();
                }
            }
        });


    }

    public void setFileterDownloadFile() {
        clipper = new VideoClipper(VideoWaterActivity.this);
        clipper.showBeauty();
        clipper.setInputVideoPath(videoUrl);
        localVideoUrl = FileUtils.getDownloadDir() + File.separator + "clipOut" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".mp4";
        GPUImageFilter gpuImageFilter = getmFilter(cureffectsBean);
        clipper.setFilter(gpuImageFilter);
        clipper.setOutputVideoPath(localVideoUrl);
        clipper.setOnVideoCutFinishListener(new VideoClipper.OnVideoCutFinishListener() {
            @Override
            public void onFinish() {
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(VIDEO_CUT_FINISH);
                }
            }

            @Override
            public void onFaile() {

            }
        });
        try {
            Log.e("hero", "-----PreviewActivity---clipVideo");
            clipper.clipVideo(0, videoPreviewView.getVideoDuration() * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initView() {
        super.initView();
        GridLayoutManager linearLayoutManager = new GridLayoutManager(this, 4);
        mFilterListView.setLayoutManager(linearLayoutManager);
        PersonalCreateConfigBean customVideoConfigure = AssetsDataUtils.getCustomVideoConfigure();
        filtersBeans = customVideoConfigure.getFilters();
        if (filtersBeans == null) return;
        filterAdapter = new FilterAdapter(this, filtersBeans, R.layout.filter_item_layout);
        mFilterListView.setAdapter(filterAdapter);
        filterAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseRecyclerHolder baseRecyclerHolder, int position, Object o) {
                filterAdapter.setSelect(position);
//                UIUtils.getHandler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        hideFilters();
//                    }
//                }, 500);

            }
        });

        closeFilterLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideFilters();
            }
        });

        animator = ObjectAnimator.ofFloat(tvTextEdit, "rotation", 0, 360);
        animator.setDuration(500);
        animator.setRepeatCount(ValueAnimator.INFINITE);
    }

    private void showFilters() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(mFilterLayout, "translationY", mFilterLayout.getHeight(), 0);
        animator.setDuration(200);
        animator.addListener(new Animator.AnimatorListener() {

            @Override
            public void onAnimationStart(Animator animation) {
                //findViewById(R.id.btn_camera_shutter).setClickable(false);
                mFilterLayout.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }
        });
        animator.start();
        isShow = !isShow;
    }

    private void hideFilters() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(mFilterLayout, "translationY", 0, mFilterLayout.getHeight());
        animator.setDuration(200);
        animator.addListener(new Animator.AnimatorListener() {

            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mFilterLayout.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                mFilterLayout.setVisibility(View.INVISIBLE);
            }
        });
        animator.start();
        isShow = !isShow;
    }


    @Override
    public void dataEvent(UserMakeTag userMakeTag) {
        if (userMakeTag.equals(UserMakeTag.CUTUPDATE)) {
            isUpdate = true;
            videoUrl = userMakeTag.getTag();
            localVideoUrl = SpUtils.getInstance().getString(videoUrl);
            videoPreviewView.setChangeVideoPath(localVideoUrl);
        }
    }


    private void switchFilterTo(final GPUImageFilter filter) {
        GPUImageFilterGroup filterGroup = new GPUImageFilterGroup();
        filterGroup.addFilter(new GPUImageExtTexFilter());
        filterGroup.addFilter(filter);
        videoPreviewView.getVideoPreviewView().setFilter(filterGroup);
        tvFilterName.setText(cureffectsBean.getName());
        new GPUImageFilterTools.FilterAdjuster(filter);

    }

    public GPUImageFilter getmFilter(EffectsBean filtersBean) {

        //颜色滤镜

        if (filtersBean.getCt() == 1602) {
            float[] doubles = new float[16];
            EffectsBean.ParamsBean params = filtersBean.getParams();
            float intensity = (float) params.getIntensity();
            List<Double> r = params.getR();
            List<Double> g = params.getG();
            List<Double> b = params.getB();
            List<Integer> a = params.getA();
            List<Double> doubles1 = new ArrayList<>();
            for (int i = 0; i < r.size(); i++) {
                doubles1.add(r.get(i));
            }
            for (int i = 0; i < g.size(); i++) {
                doubles1.add(g.get(i));
            }
            for (int i = 0; i < b.size(); i++) {
                doubles1.add(b.get(i));
            }
            for (int i = 0; i < a.size(); i++) {
                doubles1.add(TypeCastHelper.toDouble(a.get(i)));
            }
            for (int i = 0; i < doubles1.size(); i++) {
                doubles[i] = TypeCastHelper.toFloat(doubles1.get(i));
            }
            return new GPUImageColorMatrixFilter(intensity, doubles);
        } else if (filtersBean.getCt() == 1603) {
            EffectsBean.ParamsBean params = filtersBean.getParams();
            float intensity = (float) params.getIntensity();
            List<Double> color = params.getColor();
            float[] doubles = new float[3];
            for (int i = 0; i < color.size(); i++) {
                doubles[i] = TypeCastHelper.toFloat(color.get(i));
            }
            return new GPUImageMonochromeFilter(intensity, doubles);
            // mFilter=new GPUImageBrightnessFilter(0);
        } else if (filtersBean.getCt() == 1604) {
            return new GPUImageSketchFilter();
        } else if (filtersBean.getCt() == 0) {
            return new GPUImageFilter();
        } else {
            return new GPUImageFilter();
        }
    }


    public int getSelectPostion(EffectsBean effectsBean) {
        for (int i = 0; i < filtersBeans.size(); i++) {
            if (effectsBean.getName().equals(filtersBeans.get(i).getName())) {
                return i;
            }
        }
        return 0;
    }

    public class FilterAdapter extends ABaseRefreshAdapter<EffectsBean> {
        private int selected = 0;

        public FilterAdapter(Context context, List<EffectsBean> datas, int itemLayoutId) {
            super(context, datas, itemLayoutId);
        }

        public void setSelect(int position) {
            if (selected == position)
                return;
            int lastSelected = selected;
            selected = position;
            notifyItemChanged(lastSelected);
            notifyItemChanged(position);
            // notifyDataSetChanged();
            currentPosition = selected;
            cureffectsBean = filtersBeans.get(selected);
            cureffectsBean.setId(videoId);
            tvFilterName.setText(cureffectsBean.getName());
            GPUImageFilterGroup filterGroup = new GPUImageFilterGroup();
            currentFilter = getmFilter(cureffectsBean);
            filterGroup.addFilter(new GPUImageExtTexFilter());
            filterGroup.addFilter(currentFilter);
            videoPreviewView.getVideoPreviewView().setFilter(filterGroup);
            new GPUImageFilterTools.FilterAdjuster(currentFilter);
        }

        @Override
        protected void convert(BaseRecyclerHolder baseRecyclerHolder, EffectsBean filtersBean, int position) {
            ImageView thumbImage = baseRecyclerHolder.getView(R.id.filter_thumb_image);
            TextView filterName = baseRecyclerHolder.getView(R.id.filter_thumb_name);
            FrameLayout thumbSelected = baseRecyclerHolder.getView(R.id.filter_thumb_selected);
            View thumbSelected_bg = baseRecyclerHolder.getView(R.id.filter_thumb_selected_bg);
            if (position == selected) {
                thumbSelected.setVisibility(View.VISIBLE);
                thumbSelected_bg.setBackgroundColor(Color.LTGRAY);
                thumbSelected_bg.setAlpha(0.7f);
            } else {
                thumbSelected.setVisibility(View.GONE);
            }
            ImageLoader.getInstance().showImage(getContext(), filtersBean.getIcon(), thumbImage);
            filterName.setText(filtersBean.getName());
        }
    }
}
